package com.lhn.test;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpHost;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;

import java.io.IOException;

/**
 * es 客户端-创建索引
 *
 * @author lhn
 * @date 2022/07/27 22:23
 * @since 1.0.0
 **/
public class ESTest_Doc_Insert_Batch {

    public static void main(String[] args) throws IOException {
        RestHighLevelClient restHighLevelClient = null;
        try {
            restHighLevelClient = new RestHighLevelClient(RestClient.builder(new HttpHost("106.15.191.175", 9200, "http")));

            BulkRequest request = new BulkRequest();
            request.add(new IndexRequest().index("user").id("1001").source(XContentType.JSON, "name", "张三1", "age", "10", "sex", "男"));
            request.add(new IndexRequest().index("user").id("1002").source(XContentType.JSON, "name", "张三2", "age", "20", "sex", "男"));
            request.add(new IndexRequest().index("user").id("1003").source(XContentType.JSON, "name", "张三3", "age", "30", "sex", "男"));
            request.add(new IndexRequest().index("user").id("1004").source(XContentType.JSON, "name", "张三4", "age", "40", "sex", "男"));
            request.add(new IndexRequest().index("user").id("1005").source(XContentType.JSON, "name", "张三5", "age", "50", "sex", "女"));
            request.add(new IndexRequest().index("user").id("1006").source(XContentType.JSON, "name", "张三6", "age", "60", "sex", "男"));
            request.add(new IndexRequest().index("user").id("1007").source(XContentType.JSON, "name", "张三7", "age", "70", "sex", "男"));
            request.add(new IndexRequest().index("user").id("1008").source(XContentType.JSON, "name", "张三8", "age", "80", "sex", "男"));
            request.add(new IndexRequest().index("user").id("1009").source(XContentType.JSON, "name", "张三9", "age", "90", "sex", "男"));
            BulkResponse responses = restHighLevelClient.bulk(request, RequestOptions.DEFAULT);

            System.out.println(responses.getTook());
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            assert restHighLevelClient != null;
            restHighLevelClient.close();
        }
    }

}